namespace HZY.Framework.Core.CustomExceptionHandling;

public class CustomExceptionHandlingMiddleware : IMiddleware
{
    public async Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
        try
        {
            await next.Invoke(context);
        }
        catch (Exception exception)
        {
            // throw;

            if (exception is MessageBoxException messageBoxException)
            {
                var problemDetailsService = context.RequestServices.GetService<IProblemDetailsService>();
                if (problemDetailsService is null)
                {
                    throw;
                }

                var result = messageBoxException.GetResult();
                var problemDetails = new ProblemDetails
                {
                    Status = result.Code,
                    Title = result.ErrorMessage,
                    Detail = messageBoxException.Message,
                    // Type = exception.GetType().ToString(),
                    Extensions = new Dictionary<string, object?>
                    {
                        { "data", result.Data },
                        { "code", result.Code }
                    }
                };

                context.Response.StatusCode = result.Code;

                var problemDetailsContext = new ProblemDetailsContext
                {
                    HttpContext = context,
                    ProblemDetails = problemDetails,
                    Exception = exception,
                    AdditionalMetadata = context.GetEndpoint()?.Metadata,
                };

                context.Items[nameof(ProblemDetailsContext)] = problemDetailsContext;
                await problemDetailsService.TryWriteAsync(problemDetailsContext);

                return;
            }

            throw;
        }
    }
}